package com.ohuang.apkMerge

import org.dom4j.Document
import org.dom4j.io.OutputFormat
import org.dom4j.io.SAXReader
import org.dom4j.io.XMLWriter
import java.io.FileWriter


/**
 * 将xml1合并到xml2上
 */
fun mergeXml(path: String,path2: String){
    var saxReader = SAXReader()
    saxReader.encoding="utf-8"
    var saxReader1 = SAXReader()
    saxReader1.encoding="utf-8"
    var read = saxReader.read(path)
    var read1 = saxReader1.read(path2)
    var rootElement = read.rootElement
    var rootElement1 = read1.rootElement
    rootElement.elements().forEach {
            var createCopy = it.createCopy()
            rootElement1.add(createCopy)
   }

    //保存
    saveXml(path2, read1)

}

 fun saveXml(path2: String, read1: Document?) {
    try {
        var createPrettyPrint = OutputFormat.createPrettyPrint()

        createPrettyPrint.encoding = "utf-8"
        var writer = XMLWriter(FileWriter(path2), createPrettyPrint);
        writer.write(read1)
        writer.close()
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

/**
 * 根据key移除重复项
 */
fun xmlRemoveIdenticalElement(path: String,key:String="name"){
    var saxReader = SAXReader()
    saxReader.encoding="utf-8"
    var read = saxReader.read(path)
    val map =HashMap<String,Boolean>()
    var elements = read.rootElement.elements()
    elements.forEach {

        var k=it.attributeValue(key)
        if(k!=null){
            if (map.containsKey(k)){
                read.rootElement.remove(it)
            }else{
                map[k] = true
            }
        }



    }
    //保存
    saveXml(path, read)
}

